import React, { useEffect, useState, Key } from "react";
import { Button, Card, Form, Input, message, Table } from "antd";
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import {
  HospitalSetItem,
  HospitalSetList,
} from "@/api/hospital/model/hospitalSetTypes";
import type { ColumnsType } from "antd/lib/table";
import {
  reqBatchRemoveHospitalList,
  reqGetHospitalSetList,
  reqRemoveHospital,
} from "@/api/hospital/hospitalSet";
import { useForm } from "antd/lib/form/Form";
import { useNavigate } from "react-router-dom";

function HospitalSet() {
  //是否显示loading的标识
  const [loading, setLoading] = useState(false);

  // 所有选择的医院的id的数组
  const [selectedIds, setSelectedIds] = useState<Key[]>([]);
  // 定义分页相关的state数据
  // 当前页码
  const [current, setCurrent] = useState(1);
  //数据总数
  const [total, setTotal] = useState(0);
  //每页展示数量
  const [pageSize, setPageSize] = useState(5);

  //获取医院设置组件的所有数据
  const [hospitalList, setHospitalList] = useState<HospitalSetList>([]);

  //创建form对象,用于管理(收集/读取/重置)表单数据的对象
  const [form] = useForm();
  // 创建路由导航/跳转函数（点击添加按钮跳转至新界面）
  const navigate = useNavigate();

  //创建请求医院设置列表的函数 (异步请求获取医院列表显示)
  const getHospitalList = async (page = current, limit = pageSize) => {
    //请求前显示loading
    setLoading(true);
    // 返回包含所有表单数据的对象---{hosname: xxx, hoscode: yyy}
    const { hosname, hoscode } = form.getFieldsValue();
    // 请求获取分页数据
    const result = await reqGetHospitalSetList({
      page,
      limit,
      hosname,
      hoscode,
    });
    // console.log(result);
    //请求成功后隐藏loading
    setLoading(false);
    //将需要的数据从结果中解构出来
    const { total, records } = result;
    //请求成功后，更新相关数据，显示分页列表
    setTotal(total); //更新总数量
    setHospitalList(records); //更新当前页的列表

    //更新页码和每页的数量
    setCurrent(page);
    setPageSize(limit);
  };

  //创建获取表单数据的函数（点击查询按钮的回调）
  const onFinish = () => {
    //点击查询按钮后调用请求后台数据的函数
    // console.log(form.getFieldsValue());
    getHospitalList();
  };
  //点击清空按钮的回调
  const onReset = () => {
    form.resetFields(); //清空表单输入的内容
    getHospitalList(); //重新获取列表
  };
  //初始化页面操作 (初始获取分页列表显示)
  useEffect(() => {
    getHospitalList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  //删除指定id的医院
  const removeHosptal = async (id: number) => {
    //发送请求，只会删除服务器数据，客户端数据没变
    await reqRemoveHospital(id);
    message.success("删除医院成功");
    //重新获取最新医院列表
    getHospitalList(current, pageSize);
  };

  //批量删除
  const batchRemoveHospitalList = async () => {
    //请求批量删除
    await reqBatchRemoveHospitalList(selectedIds);
    //提示成功信息
    message.success("批量删除成功");
    // 重新获取最新医院列表
    getHospitalList(current, pageSize);
  };

  //设置表头信息
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      width: 80,
      align: "center",
      // render 三个参数  x :当前对应的单个数据  y: 当前的一行数据  index:下标
      render: (x: any, y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
      align: "center",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
      align: "center",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
      align: "center",
    },
    {
      title: "签名",
      dataIndex: "signKey",
      align: "center",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
      align: "center",
    },
    {
      title: "联系人手机号",
      dataIndex: "contactsPhone",
      align: "center",
    },
    {
      title: "操作",
      render: (row) => {
        return (
          <>
            <Button
              icon={<EditOutlined />}
              onClick={() => {
                navigate(`/syt/hospital/hospitalSet/edit/${row.id}`);
              }}
              type="primary"
            ></Button>
            <Button
              onClick={() => removeHosptal(row.id)}
              className="ml"
              danger
              type="primary"
              icon={<DeleteOutlined />}
            ></Button>
          </>
        );
      },
      fixed: "right", // 固定当前列在右侧
      align: "center", //居中
    },
  ];

  return (
    <Card>
      {/* 顶部搜索 */}
      <Form form={form} onFinish={onFinish} onReset={onReset} layout="inline">
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            查询
          </Button>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="default" htmlType="reset">
            清空
          </Button>
        </Form.Item>
      </Form>

      {/* 添加和批量删除 */}
      <div className="h-20">
        <Button
          type="primary"
          onClick={() => {
            navigate("add");
          }}
        >
          添加
        </Button>
        {/* 如果没有选择一个医院，就禁用按钮 */}
        <Button
          disabled={selectedIds.length === 0}
          className="ml"
          type="default"
          onClick={batchRemoveHospitalList}
        >
          批量删除
        </Button>
      </div>

      {/* 表格数据   */}
      <Table
        dataSource={hospitalList}
        columns={columns}
        rowKey={"id"}
        scroll={{ x: "1400px" }}
        className="h-20"
        bordered
        loading={loading}
        rowSelection={{
          type: "checkbox", //设置多选框
          // 选择发生改变的回调
          // selectedRowKeys: 所有选择医院的id数组
          // selectedRows: 所有选择项医院的数组
          onChange: (
            selectedRowKeys: Key[],
            selectedRows: HospitalSetItem[]
          ) => {
            // 保存所有选择项的id的数组
            console.log(selectedRowKeys);

            setSelectedIds(selectedRowKeys);
          },
        }}
        //分页相关
        pagination={{
          current, //当前页码
          total, //总数量
          pageSize, //每页数量
          showQuickJumper: true, //是否快速跳转至某页
          showSizeChanger: true, //是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
          pageSizeOptions: [3, 5, 8, 10], //指定每页可以显示多少条
          showTotal: (total) => `总共 ${total} 条`, //用于显示数据总量和当前数据顺序
          onChange: getHospitalList, // 当页码或每页数量发生改变时调用
        }}
      />
    </Card>
  );
}

export default HospitalSet;
